<template>
    <div class="assignment">
        <!-- 分配客户 -->
        <el-dialog title="客户分配" :visible.sync="assignVisible" width="30%" :close-on-press-escape="false" :close-on-click-modal="false">
            <p>可分配数据{{ assignTotal }}条</p>
            <el-divider></el-divider>
            <div class="assign">
                <el-form ref="form" :model="form" label-width="100px">
                    <el-form-item label="分配方式">
                        <el-radio-group v-model="form.assignRadio" @change="resetForm">
                            <!-- <el-radio label="1" v-if="loginId === 1">分配到分公司</el-radio> -->
                            <el-radio label="2" v-if="loginId != 4">分配到机构</el-radio>
                            <el-radio label="3">分配到业务员</el-radio>
                            <el-radio label="4" v-if="loginId === 2">分配到中支</el-radio>
                            <el-radio label="5" v-if="loginId === 4">分配到运营组</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="选择分公司" v-if="form.assignRadio == 1">
                        <el-select v-model="form.affiliate" placeholder="请选择">
                            <el-option v-for="item in affiliateOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择机构" v-if="form.assignRadio == 2">
                        <template>
                            <mechanism-cascader :deptId.sync="form.deptId">
                            </mechanism-cascader>
                        </template>
                    </el-form-item>
                    <el-form-item label="选择中支" v-if="form.assignRadio == 4">
                        <el-select v-model="form.ramus" placeholder="请选择">
                            <el-option v-for="item in ramusOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择运营组" v-if="form.assignRadio == 5">
                        <el-select v-model="form.operate" placeholder="请选择">
                            <el-option v-for="item in operateOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="assignMain" v-if="form.assignRadio == 3">
                    <el-input v-model="assignNum" placeholder="请输入数量" class="inputRenNum"
                        onkeyup="value=value.replace(/[^\d]/g,'')">
                    </el-input>/人
                    <div class="tagNames">
                        <el-tag :key="tag.userId" v-for="tag in checkedSales" closable :disable-transitions="false"
                            @close="handleClose(tag)">
                            {{ tag.userName }}
                        </el-tag>
                    </div>
                    <el-input v-model="assignName" placeholder="请输入销售姓名" @change="searchWeUser" style="width: 50%">
                    </el-input>
                    <el-checkbox-group v-model="checkedSales" @change="handleCheckedSalesChange" class="selectBox">
                        <el-checkbox v-for="item in sales" :label="item" :key="item.userId" :class="[
                            checkList.includes(item.userId)
                                ? 'nameSelect nameSelectActive'
                                : 'nameSelect',
                        ]">
                            <div class="nameNum">
                                {{ item.userName }}
                                <el-input v-model="item.num" v-if="checkList.includes(item.userId)" placeholder="请输入数量"
                                    onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
                            </div>
                        </el-checkbox>
                    </el-checkbox-group>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                    </el-checkbox>
                </div>
            </div>
            <div slot="footer">
                <el-button type="primary" @click="activeAssign()">立即分配</el-button>
                <el-divider></el-divider>
            </div>
        </el-dialog>
        <el-dialog title="分配结果" :visible.sync="assignResultVisible" width="30%">
            <div>
                <p>本次已分配线索数:{{ assignTotal }}条</p>
            </div>
            <div slot="footer">
                <el-button type="primary" @click="assignResult">返回</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import mechanismCascader from "@/components/mechanismCascader.vue";
import { getAllWeUser } from "@/api/customer/customerManage";
export default {
    props: {
        assignTotal: Number,
    },
    components: {
        mechanismCascader,
    },
    data() {
        return {
            loginId: 1,
            assignVisible: false,
            assignResultVisible: false,
            affiliateOptions: [
                {
                    value: "选项1",
                    label: "黄金糕",
                },
            ],
            ramusOptions: [
                {
                    value: "选项2",
                    label: "黄金糕",
                },
            ],
            operateOptions: [
                {
                    value: "选项4",
                    label: "黄金糕",
                },
            ],
            form: {
                assignRadio: null,
                affiliate: "", //分公司
                deptId: null, //机构
                ramus: "", //中支
                operate: "", //运营组
            },
            // 分配到业务员
            assignNum: "",
            checkedSales: [],
            assignName: "",
            sales: [],
            checkList: [],
            isIndeterminate: false,
            checkAll: false,
        };
    },
    mounted() {
        const params = {
            department: "",
            userName: "",
        };
        this.getAllWeUser(params);
    },
    watch: {
      assignName: {
        handler(newValue) {
          let this_ = this
          const params = {
            department: "",
            userName: newValue,
          };
          this_.getAllWeUser(params);
        },
        deep: true
      }
    },
    methods: {
        openDialog() {
            this.assignVisible = true;
            this.resetAssign();
        },
        closeDialog() {
            this.assignVisible = false;
        },
        openResultDialog() {
            this.closeDialog();
            this.assignResultVisible = true;
        },
        activeAssign() {
            if (this.assignChecked()) {
                let assignForm = {
                    type: this.form.assignRadio,
                    weUserIdList: [],
                    deptId: this.form.deptId,
                };
                if (this.form.assignRadio == 3) {
                } {
                    this.checkedSales.forEach(item => {
                        if (item.num) {
                            assignForm.weUserIdList.push({ weUserId: item.userId, num: item.num })
                        } else {
                            assignForm.weUserIdList.push({ weUserId: item.userId, num: this.assignNum })
                        }
                    });
                };
                this.$emit("sendAssignInfo", assignForm);
            } else {
                this.$message.error('选择客户和分配数量不匹配');
            }
        },
        // 分配全选
        handleCheckAllChange(val) {
            this.checkedSales = val ? this.sales : [];
            this.isIndeterminate = false;
            this.checkInputHide();
        },
        handleCheckedSalesChange(value) {
            this.checkInputHide();
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.sales.length;
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.sales.length;
        },
        checkInputHide() {
            // 点击出现input框
            this.checkList = [];
            this.checkedSales.forEach((item) => {
                this.checkList.push(item.userId);
            });
        },
        handleClose(tag) {
            this.checkedSales.splice(this.checkedSales.indexOf(tag), 1);
            this.checkInputHide();
        },
        // 获取全部员工
        getAllWeUser(params) {
            getAllWeUser(params)
                .then((res) => {
                    if (res.code === 200) {
                        this.sales = res.data || [];
                        this.sales.forEach((item, index) => {
                            this.$set(this.sales, index, { ...item, num: "" });
                        });
                        this.checkedSales = [];
                        this.checkInputHide();
                    }
                })
                .catch(() => {
                    console.log("error submit!!");
                });
        },
        // 搜索员工
        searchWeUser() {
          // console.log('触发查询')
          //   const params = {
          //       department: "",
          //       userName: this.assignName,
          //   };
          //   this.getAllWeUser(params);
        },
        resetForm() {
            this.form.affiliate="";
            this.assignNum = "";
            this.checkedSales = [];
            this.checkList = [];
        },
        // 分配重置
        resetAssign() {
            this.assignNum = "";
            this.checkedSales = [];
            this.checkList = [];
            this.sales.forEach((item, index) => {
              this.$set(this.sales, index, { ...item, num: "" });
            })
            this.form = {
                assignRadio: null,
                affiliate: "", //分公司
                ramus: "", //中支
                deptId: null, //机构
                operate: "", //运营组
            };
        },
        // 分配校验
        assignChecked() {
            let count = 0;
            this.checkedSales.forEach(item => {
                if (item.num) {
                    count += Number(item.num);
                } else {
                    count += Number(this.assignNum);
                }
            });
            if (this.form.assignRadio == 3 && this.assignTotal != count) {
                return false
            } else {
                return true
            }
        },
        assignResult(){
            this.assignResultVisible=false;
            this.$emit("sendResult")
        },
    },
};
</script>
<style lang="scss" scoped>
.assignMain {
    margin-left: 38px;
}

.inputRenNum {
    width: 40%;
    margin-right: 10px;
}

.el-input {
    margin-top: 5px;
    margin-bottom: 5px;
}

.nameSelect {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 0 10px;
    margin: 2px 0;
}

.nameSelectActive {
    background: #ffeeeb;
}

.selectBox {
    width: 100%;
    height: 150px;
    overflow-y: scroll;
    margin-top: 10px;
}

.tagNames {
    // height: 50px;
    overflow-y: scroll;
}

.nameNum {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-input {
        width: 130px;
    }
}

::v-deep {
    .el-checkbox__label {
        width: 100%;
    }
}
</style>
